package com.harmontronics.hanma.paas.paas.domain.iam.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.harmontronics.hanma.paas.paas.domain.iam.repository.mapper.HmMenuMapper;
import com.harmontronics.hanma.paas.paas.domain.iam.repository.persistence.HmMenuRepository;
import com.harmontronics.hanma.paas.paas.domain.iam.entity.HmMenu;
import com.harmontronics.hanma.paas.paas.utils.MyBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.harmontronics.hanma.paas.paas.common.PageBase;

import com.harmontronics.hanma.paas.paas.domain.iam.repository.po.HmMenuPO;
import java.util.List;

/**
 * @author 吕大兵
 */
@Service("hmMenuService")
@DS("#header.App-Unique")
public class HmMenuService {

    @Autowired
    private HmMenuRepository hmMenuRepository;

    @Autowired
    private HmMenuMapper hmMenuMapper;


    public HmMenu findById( Long id) {
            HmMenuPO po = hmMenuRepository.getById(id);
        return BeanUtil.toBean(po,HmMenu. class);
    }

    public void save(HmMenu hmMenu) {
            HmMenuPO po = BeanUtil.toBean(hmMenu,HmMenuPO.class);
            hmMenuRepository.save(po);
    }

    public void update(HmMenu hmMenu) {
            HmMenuPO po = BeanUtil.toBean(hmMenu,HmMenuPO.class);
            hmMenuRepository.updateById(po);
    }

    public void remove(List<Long> ids) {
            hmMenuRepository.removeByIds(ids);
    }

    public List<HmMenu> getList() {
        List<HmMenuPO> pos = hmMenuRepository.list(new QueryWrapper<HmMenuPO>().orderByAsc("serial_num"));
        return Convert.toList(HmMenu. class,pos);
    }

    public PageBase<HmMenu> getList(int pageNo, int pageSize) {
        Page<HmMenuPO> page = new Page<>(pageNo, pageSize);
        IPage<HmMenuPO> resultPage =
                    hmMenuRepository.selectPage(Wrappers.emptyWrapper(), page);
        return PageBase.from(resultPage,HmMenu. class);
    }

    /**
     * 检测页面是否被菜单引用
     * @param pageId 页面ID
     * @return
     */
    public boolean isPageReferred(Long pageId){
        return hmMenuRepository.existsByPage(pageId);
    }

    public List<Long> selectMenuIdsWithGroupId(List<Long> groupIds){
        return hmMenuMapper.selectMenuIdsWithGroupId(groupIds);
    }

    public List<HmMenu> getMenuWithIds(List<Long> menuIdList){
        QueryWrapper<HmMenuPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",menuIdList).orderByAsc("serial_num");
        List<HmMenuPO> menuPOList = hmMenuRepository.list(queryWrapper);
        return MyBeanUtils.batchTransform(HmMenu.class,menuPOList);
    }

}